package com.jvtd.nettyim.im.server.handler;

import com.jvtd.nettyim.im.protocol.request.MessageRequestPacket;
import com.jvtd.nettyim.im.protocol.response.MessageResponsePacket;
import com.jvtd.nettyim.im.session.Session;
import com.jvtd.nettyim.im.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Created by neal.zhang
 * @date 2020/5/29 - 20:17
 */
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket msg) throws Exception {
        System.err.println("收到客户端消息..." + msg.getMessage());
        Session session = SessionUtil.getSession(ctx.channel());
        MessageResponsePacket messageResponse = new MessageResponsePacket();
        messageResponse.setFromUserId(session.getUserId());
        messageResponse.setFromUserName(session.getUserName());
        messageResponse.setMessage(msg.getMessage());

        Channel toUserChannel = SessionUtil.getChannel(msg.getToUserId());
        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponse);
        } else {
            System.err.println("[" + msg.getToUserId() + "] 离线，发送失败.");
        }
    }
}
